package org.dromara.system.service.impl;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.Commission;
import org.dromara.system.domain.Store;
import org.dromara.system.mapper.CommissionMapper;
import org.dromara.system.mapper.StoreMapper;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.SalesDataBo;
import org.dromara.system.domain.vo.SalesDataVo;
import org.dromara.system.domain.SalesData;
import org.dromara.system.mapper.SalesDataMapper;
import org.dromara.system.service.ISalesDataService;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 销售数据信息Service业务层处理
 *
 * @author joker
 * @date 2025-05-05
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SalesDataServiceImpl implements ISalesDataService {

    private final SalesDataMapper baseMapper;
    private final CommissionMapper commissionMapper;
    private final StoreMapper storeMapper;

    /**
     * 查询销售数据信息
     *
     * @param salesId 主键
     * @return 销售数据信息
     */
    @Override
    public SalesDataVo queryById(Long salesId) {
        return baseMapper.selectVoById(salesId);
    }

    /**
     * 分页查询销售数据信息列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 销售数据信息分页列表
     */
    @Override
    public TableDataInfo<SalesDataVo> queryPageList(SalesDataBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SalesData> lqw = buildQueryWrapper(bo);
        Page<SalesDataVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);

        // 查询全部店铺
        List<Store> storeList = storeMapper.selectList();
        Map<Long, Store> storeMap = StreamUtils.toIdentityMap(storeList, Store::getStoreId);

        result.getRecords().forEach(vo -> {
            Store store = storeMap.get(vo.getStoreId());
            if (store != null) {
                vo.setStoreName(store.getStoreName());
            }
        });
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的销售数据信息列表
     *
     * @param bo 查询条件
     * @return 销售数据信息列表
     */
    @Override
    public List<SalesDataVo> queryList(SalesDataBo bo) {
        LambdaQueryWrapper<SalesData> lqw = buildQueryWrapper(bo);
        List<SalesDataVo> voList = baseMapper.selectVoList(lqw);
        // 查询全部店铺
        List<Store> storeList = storeMapper.selectList();
        Map<Long, Store> storeMap = StreamUtils.toIdentityMap(storeList, Store::getStoreId);

        voList.forEach(vo -> {
            Store store = storeMap.get(vo.getStoreId());
            if (store != null) {
                vo.setStoreName(store.getStoreName());
            }
        });
        return voList;
    }

    private LambdaQueryWrapper<SalesData> buildQueryWrapper(SalesDataBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SalesData> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(SalesData::getSalesId);
        lqw.eq(bo.getStoreId() != null, SalesData::getStoreId, bo.getStoreId());
        lqw.eq(bo.getSalesQuantity() != null, SalesData::getSalesQuantity, bo.getSalesQuantity());
        lqw.eq(bo.getSalesTime() != null, SalesData::getSalesTime, bo.getSalesTime());
        lqw.like(StringUtils.isNotBlank(bo.getProductName()), SalesData::getProductName, bo.getProductName());
        lqw.eq(bo.getSingleItemCommission() != null, SalesData::getSingleItemCommission, bo.getSingleItemCommission());
        lqw.eq(bo.getCommissionMoney() != null, SalesData::getCommissionMoney, bo.getCommissionMoney());
        lqw.eq(bo.getPlatformServiceFee() != null, SalesData::getPlatformServiceFee, bo.getPlatformServiceFee());
        lqw.eq(bo.getOrderDispatchedNumber() != null, SalesData::getOrderDispatchedNumber, bo.getOrderDispatchedNumber());
        lqw.eq(bo.getActivationQuantity() != null, SalesData::getActivationQuantity, bo.getActivationQuantity());
        lqw.eq(bo.getShipmentRate() != null, SalesData::getShipmentRate, bo.getShipmentRate());
        lqw.eq(bo.getShipmentActivationRate() != null, SalesData::getShipmentActivationRate, bo.getShipmentActivationRate());
        lqw.eq(bo.getActivationRate() != null, SalesData::getActivationRate, bo.getActivationRate());
        lqw.eq(bo.getShippedQuantity() != null, SalesData::getShippedQuantity, bo.getShippedQuantity());
        return lqw;
    }

    /**
     * 新增销售数据信息
     *
     * @param bo 销售数据信息
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(SalesDataBo bo) {
        SalesData add = MapstructUtils.convert(bo, SalesData.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setSalesId(add.getSalesId());
        }
        return flag;
    }

    /**
     * 修改销售数据信息
     *
     * @param bo 销售数据信息
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(SalesDataBo bo) {
        SalesData update = MapstructUtils.convert(bo, SalesData.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SalesData entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除销售数据信息信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Async
    @Override
    public void asyncInsertSalesData(String creationTime, Long operUserId) {
        String commissionValidityPeriod = creationTime.substring(0, 7);
        List<Commission> commissionList = commissionMapper.selectList(
            new LambdaQueryWrapper<Commission>().eq(Commission::getCommissionValidityPeriod, commissionValidityPeriod));
        Map<String, Commission> commissionMap = StreamUtils.toIdentityMap(commissionList, Commission::getCommissionName);

        // 查询全部店铺
        List<Store> storeList = storeMapper.selectList();
        Map<String, Store> storeMap = StreamUtils.toIdentityMap(storeList, Store::getStoreName);

        List<SalesData> salesDataList = baseMapper.selectOrderSalesDataGroupByList(creationTime);
        log.info("查询到的订单销售数据{}", JSONUtil.toJsonStr(salesDataList));
        List<SalesData> dataList = StreamUtils.toList(salesDataList, salesData -> {
            Commission commission = commissionMap.get(salesData.getProductName());
            if (ObjectUtils.isNotNull(commission)) {
                salesData.setTenantId(commission.getTenantId());
                // 单品佣金
                BigDecimal singleItemCommission = new BigDecimal(commission.getCommissionMoney());
                salesData.setSingleItemCommission(singleItemCommission);
                // 佣金（激活量*单品佣金）
                BigDecimal commissionMoney = new BigDecimal(salesData.getActivationQuantity()).multiply(singleItemCommission);
                salesData.setCommissionMoney(commissionMoney);
                // 店铺id
                Store store = storeMap.get(salesData.getProductName());
                if (ObjectUtils.isNotNull(store)) {
                    salesData.setStoreId(store.getStoreId());
                }
            }
            salesData.setSalesTime(creationTime);
            salesData.setCreateBy(operUserId);
            return salesData;
        });
        // 先删除会计数据，在新增
        baseMapper.delete(Wrappers.<SalesData>lambdaUpdate().eq(SalesData::getSalesTime, creationTime));
        baseMapper.insertBatch(dataList);
    }
}
